#
#===============================================================================
#
#         FILE:  Calc.pm
#
#  DESCRIPTION:  
#
#        FILES:  ---
#         BUGS:  ---
#        NOTES:  ---
#       AUTHOR:   (), <>
#      COMPANY:  
#      VERSION:  1.0
#      CREATED:  04/14/2010 11:43:45 PM GMT
#     REVISION:  ---
#===============================================================================

use strict;
use warnings;

package GoogPl::Calc;

use LWP::UserAgent;
use URI::Escape qw( uri_escape );
use JSON::XS;

sub register {
    my $self = shift;

    return ('cmd' => 'calc', 'pat' => '^!calc\s+(.*)');
}

sub help {
    my $self = shift;

    return ('Get Google calculator results. Can be used for math (2 + 2) or unit conversions (2km in mi)');
}

sub process_command {
    my $self = shift;
    my ($kernel, $sender, $nickhost, $target, $msgtxt, %conf) = @_;

    $msgtxt =~ /^!calc\s+(.*)/;

    my $ua = LWP::UserAgent->new;
    my $res = $ua->get("http://www.google.com/ig/calculator?hl=en&q=".uri_escape($1));

    my $c = $res->decoded_content;
    $c =~ s/lhs:/"lhs":/;
    $c =~ s/rhs:/"rhs":/;
    $c =~ s/icc:/"icc":/;
    $c =~ s/error:/"error":/;

    use utf8;
    if( ! utf8::is_utf8($c) ) {
	utf8::encode($c);
    }
    my $j = decode_json($c);

    return if ! $j;

    $kernel->post($sender => privmsg => $target => $j->{'rhs'} ? $j->{'rhs'} : 'error'.$j->{'error'});
}

1;
